<?php

namespace hamster\mongodb;


use MongoDB\Client;

class Model
{
	use Where;
	use Query;
	
	/**
	 * 数据库链接
	 * @var string
	 */
	protected static $connection;

	/**
	 * 数据库配置
	 * @var array
	 */
	protected static $config = [];

	/**
	 * 数据库名称
	 * @var string
	 */
	protected static $db_name;

	/**
	 * 数据库对象
	 * @var object
	 */
	protected static $db;

	/**
	 * Client对象
	 * @var string
	 */
	protected static $client;

	/**
	 * 模型名称
	 * @var string
	 */
	protected $name;

	/**
	 * 集合名称
	 * @var string
	 */
	protected $collection;

	/**
	 * 数据
	 * @var array
	 */
	protected $data;

	/**
	 * 是否自增id
	 * @var bool
	 */
	protected $auto_increment = false;

	/**
	 * Model constructor.
	 */
	public function __construct()
	{
		if (empty($this->name)) {
			// 当前模型名
			$name       = str_replace('\\', '/', static::class);
			$this->name = basename($name);
		}
		$this->collection = (self::$config['prefix'] ?? '') . $this->name;

		self::$db_name = $db_name = self::$config['db'] ?? 'hamster';

		if (self::$client) {
			self::$db = self::$client->$db_name;
		}
	}

	/**
	 * 设置连接
	 * @param array $config mongo连接配置
	 */
	public static function setConnection($config)
	{
		self::$config = $config;
		$connection   = 'mongodb://' . ($config['username'] ? "{$config['username']}" : '') . ($config['password'] ? ":" . urlencode($config['password']) . "@" : '') . $config['host'] . ($config['port'] ? ":{$config['port']}" : '') . '/' . ($config['database'] ? "{$config['database']}" : '');

		self::$connection = $connection;
		self::$client = new Client($connection);
	}

	/**
	 * 获取连接
	 * @return string
	 */
	public static function getConnection()
	{
		return self::$connection;
	}

	/**
	 * 获取连接配置
	 * @return array
	 */
	public static function getConfig()
	{
		return self::$config;
	}

	/**
	 * 设置数据库名称
	 * @param string $db_name
	 */
	public static function setDbName($db_name = '')
	{
		self::$db_name = $db_name;
		if (self::$client) {
			self::$db = self::$client->$db_name;
		}
	}

	/**
	 * 获取数据库名称
	 * @return mixed|string
	 */
	public static function getDbName()
	{
		return self::$db_name;
	}

	
}